package demo2;

import com.fasterxml.jackson.core.type.TypeReference;
import com.fasterxml.jackson.databind.ObjectMapper;
import org.junit.Test;

import java.util.ArrayList;
import java.util.HashMap;

public class ObjectMapperTest {
    ObjectMapper mapper =new ObjectMapper();

    //User对象转json
    @Test
    public void test1()throws Exception{
        User user =new User("路明非",20);
        String json = mapper.writeValueAsString(user);
        System.out.println("json:"+json);


        //json转User对象
        User user2 = mapper.readValue(json,User.class);
        System.out.println("java:"+user2);
    }


    //Map转 JSON
    @Test
    public void test2()throws Exception{
        HashMap<String,String>map = new HashMap<>();
        map.put("名字","诺诺");
        map.put("性别","女");
        String json = mapper.writeValueAsString(map);
        System.out.println(json);

        //json转map
        HashMap<String,String>map2 =mapper.readValue(json,HashMap.class);
        System.out.println(map2);
    }

    //Map转 JSON 后面是任意类型
    @Test
    public void test3()throws Exception{
        HashMap<String,User>map = new HashMap<>();
        map.put("1班",new User("奥特曼",122));
        String json = mapper.writeValueAsString(map);
        System.out.println(json);

        //json转map
        HashMap<String,User>map2 =mapper.readValue
                (json,new TypeReference<HashMap<String,User>>(){});
        System.out.println(map2);
    }


    @Test
    public void test4()throws Exception{
        //List转 JSON
        ArrayList<String>list = new ArrayList<>();
        list.add("傻子");
        list.add("哈卵");
        String json = mapper.writeValueAsString(list);
        System.out.println(json);
        //json转 List
        ArrayList<String>list2 = mapper.readValue(json, ArrayList.class);
        System.out.println(list2);
    }


    @Test
    public void test5()throws Exception{
        //List转 JSON
        ArrayList<User>list = new ArrayList<>();
        list.add(new User("莫瑞",13));
        list.add(new User("蒂克",100));
        String json = mapper.writeValueAsString(list);
        System.out.println(json);
        //json转 List
        ArrayList<String>list2 = mapper.readValue(json, new TypeReference<ArrayList<User>>(){});
        System.out.println(list2);
    }


}
